import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { staticRoutes, dynamicRoutes, all_permission } from './route'
import { useRoutesStore, useUserStore } from '@/stores'
import { Session } from '@/utils/storage'


/**
 * 创建路由实例
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes,
})


/**
 * 路由多级嵌套数组处理成一维数组
 * @param arr 传入路由菜单数据数组
 * @returns 返回处理后的一维路由菜单数组
 */
export function formatFlatteningRoutes(arr: any) {
  if (arr.length <= 0) return false;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children) {
      arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
    }
  }
  return arr
}

let filterPermission = (routes: any[]) => {
  const userPermissions = Session.get('permissions')
  if (userPermissions.length === 1 && userPermissions[0] === all_permission) {
    return routes
  }
  let newarr: any[] = []
  routes.forEach(item => {
    if (item.children && item.children.length) {
      let children = filterPermission(item.children)
      let obj = {
        ...item,
        children
      }
      if (children && children.length) {
        newarr.push(obj)
      }
    } else {
      if (item.permissions === all_permission || item.permissions?.some((j: string) => userPermissions.includes(j))) {
        newarr.push(item)
      }
    }
  })
  return newarr
}


/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes（/@/router/route）第一个顶级 children 的路由一维数组，非多级嵌套
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 */
export function setAddRoute() {
  if (!Session.get('token')) { return false }
  const hasPermissionRoutes = filterPermission(dynamicRoutes)
  let filterRouteEnd: any = formatFlatteningRoutes(hasPermissionRoutes);
  filterRouteEnd.forEach((route: RouteRecordRaw) => {
    const routeName: any = route.name;
    if (!router.hasRoute(routeName)) router.addRoute(route);
  });
  return filterRouteEnd[0].children
}

// 初始化路由
setAddRoute()

// 路由加载前
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const routesStore = useRoutesStore()
  if (to.path === '/login') {
    next()
  } else {
    if (Session.get('token')) {
      // 添加动态路由
      const routerRes = await setAddRoute()
      routesStore.setRoutesList(routerRes)
      next()
    } else {
      ElMessage.warning("请先登录")
      next('/login')
    }
  }
})

// 路由加载后
router.afterEach(() => {
  NProgress.done()
})

export default router